#!/bin/bash -e
#
# Use Skip native back end and binaryen tools
# (https://github.com/WebAssembly/binaryen) to
# convert Skip to WebAssembaly (wasm)
#
# Example usage:
#  $ ./skip_to_wasm -o

DIR="$(dirname "$0")"
SKIP=$DIR/../../..

while getopts ":o:" opt; do
  case $opt in
    o)
      outfile=$OPTARG
      ;;
    \?)
      echo "Invalid option: -$OPTARG" >&2
      exit 1
      ;;
    :)
      echo "Option -$OPTARG requires an argument." >&2
      exit 1
      ;;
  esac
done
shift $(($OPTIND - 1))

# For now -- should probably really use a temp dir when we productionize
OUTDIR=./out

bnm=`basename -s .wasm $outfile`
LLFILE=$OUTDIR/"$bnm".ll
SFILE=$OUTDIR/"$bnm".s
WATFILE=$OUTDIR/"$bnm".wat

# uncomment for debugging this script:
# set -x

# fail entire script if any command fails:
set -e

if [ ! -d $OUTDIR ]; then
  mkdir -p $OUTDIR
fi

# Use Native Back end to generate initial LLVM bitcode (.ll):
export SKIP_NBE_FLAGS=--wasm
$SKIP/tests/runtime/tools/skip_to_native --m32 --emit-llvm --via-backend $SKIP/build/bin -o $LLFILE "$@"

# Use binaryen's clang to construct a wasm32 .s file from LLVM bitcode
$SKIP/third-party/assemblyscript-runtime/node_modules/webassembly/tools/bin/darwin-x64/clang $LLFILE -S -Oz \
    -mlittle-endian --target=wasm32-unknown-unknown -nostdinc -nostdlib -o $SFILE > $OUTDIR/clang.out

# Convert .s file produced by clang to WASM S-expression syntax (wast):
$SKIP/third-party/assemblyscript-runtime/node_modules/webassembly/tools/bin/darwin-x64/s2wasm $SFILE --import-memory --global-base 64 --allocate-stack 4000 -o $WATFILE

# Convert WAST file to WASM binary encoding using wabt:
$SKIP/third-party/wabt/bin/wat2wasm --debug-names $WATFILE -o $outfile
